import 'dart:io';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/util/DataUtil.dart';
import 'package:flutter_app/util/ToastUtil.dart';
import 'package:flutter_app/util/event_bus.dart';
import 'package:flutter_app/util/oktoast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'HttpManager.dart';
import 'entity/json_to_covernt.dart';

/**
 * dio 是一个强大的Dart Http请求库，支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等...

    pub 地址：https://pub.flutter-io.cn/packages/dio

    Github 地址：https://github.com/flutterchina/dio
 */

class NetDioWidget extends StatefulWidget {
  final String ?text;

  NetDioWidget({this.text}) : super();

  @override
  State<StatefulWidget> createState() {
    return _NetDioState();
  }
}

class _NetDioState extends State<NetDioWidget> {
  var list = DataUtil.getNetType();
  var titile;
  String ?imagePath;
  var eventFir;

  @override
  void initState() {
    super.initState();
    //监听
    eventFir = eventBus.on<EventShow>().listen((event) {
      EasyLoading.dismiss();
      setState(() {
        titile = event.obj.desc;
        imagePath = event.obj.imagePath;
      });
    });
    titile = "请点击get";
    imagePath = "";
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    eventFir.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return FlutterEasyLoading(
      child: Scaffold(
          appBar: AppBar(
            title: Text("数据存储、网络请求"),
          ),
          body: new Column(
            children: [
              Container(
                padding: EdgeInsets.only(top: 20, left: 20, right: 20),
                alignment: Alignment.center,
                width: 300,
                height: 80,
                child: GestureDetector(
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.red, Colors.black38]),

                        //背景渐变
                        borderRadius: BorderRadius.circular(3.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey,
                              offset: Offset(2.0, 2.0),
                              blurRadius: 4.0)
                        ]),
                    child: Center(
                      child: Text(
                        "get请求",
                        style: TextStyle(fontSize: 20, color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    getHttp();
                  },
                ),
              ),
              SizedBox(
                height: 30,
              ),
              Container(
                alignment: Alignment.center,
                width: 200,
                height: 100,
                color: Colors.deepOrange,
                child: Text(
                  "title\n $titile",
                  style: TextStyle(color: Colors.white),
                ),
              ),
              SizedBox(
                height: 20,
              ),
              new Align(
                  alignment: Alignment.center,
                  heightFactor: 2.0,
                  child: Image(
                    image: _buildImage(),
                    // placeholder: AssetImage("assets/images/women_one.jpg"),
                    //占位图片（本地文件）,
                    width: 300.0,
                    height: 200.0,
                    fit: BoxFit.cover, //该属性用于在图片的显示空间和图片本身大小不同时指定图片的适应模式
                  )),
            ],
          )),
    );
  }

  _buildImage() {
    if (imagePath!.isNotEmpty) {
      return NetworkImage(imagePath!);
    }
    return AssetImage("assets/images/women_one.jpg"); //占位图片（本地文件）,
    // return Container();
  }
}

Future<bool> isConnected() async {
  var connectivityResult = await (Connectivity().checkConnectivity());
  return connectivityResult != ConnectivityResult.none;
}

void getHttp() {
  if (isConnected() != null) {
    isConnected().then((value) => {
          if (value)
            {
              HttpManager().getRequest("/banner/json", success: (dataJson) {
                // print('我的名字叫${name}');
                Json_to_covernt list = Json_to_covernt.fromJson(dataJson);

                print("HTTP " + "回调成功----  ");
                // 调用 eventBus.fir 发送事件信息
                eventBus.fire(EventShow(list.data![0]));
              }, error: (code, msg) {

              })
            }
          else
            {
              print("我没网络"),
              ToastUtil.toastShort("网络断开！"),
            }
        });
  }
}
